package com.atguigu.tingshu.common.login;

import ch.qos.logback.core.joran.spi.NoAutoStart;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.ReactiveRedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author NJG
 * @version 1.0
 * @date 2025/7/21 18:40
 * @description
 */
@Slf4j
@Aspect
@Component
public class GuiGuLoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 为了代码规范：认证状态校验注解只能用在api包下，且只有使用@GuiGuLogin注解的方法才能被增强
     *
     * @param pjp 目标方法对象
     * @return
     * @throws Throwable
     */

    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(guiGuLogin)")
    public Object loginAspect(ProceedingJoinPoint pjp, GuiGuLogin guiGuLogin) throws Throwable {

        log.info("前置逻辑");
        //1.获取用户令牌 用taken去redis中查询用户信息
        //1.1 获取请求对象
        //1.1.1 获取请求上下文对象 RequestAttributes是接口
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //1.1.2 获取请求对象 ServletRequestAttributes是实现类
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //1.2 获取用户令牌
        String token = request.getHeader("token");

        //2.查询当时在登录成功后存入redis中用户基本信息 UserInfoVo
        //2.1. 构建查询用户信息Redis的Key 注意：一定要跟登录成功存入Redis一致
        String redisKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;

        //获取用户信息
        UserInfoVo userInfoVo = (UserInfoVo) redisTemplate.opsForValue().get(redisKey);

        if (guiGuLogin.required() && userInfoVo == null){
            //没有登陆,诱导用户去登录
            log.error("用户未登录,请去先登陆");
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }

        //4.如果查询Redis存在用户信息，将用户ID存入ThreadLocal中方便JavaEE三层任意层获取用户ID
        if(userInfoVo != null){
            AuthContextHolder.setUserId(userInfoVo.getId());
        }


        log.info("目标方法执行");
        Object retVAl = pjp.proceed();
        log.info("后置逻辑");

        //5.清理ThreadLocal防止内存泄漏
        AuthContextHolder.removeUserId();
        return retVAl;
    }
}
